﻿using Elio.Controls;
using Elio.Interfaces;
using Elio.Sessions;
using Elio.Sessions.Widgets;
using Google.Protobuf.WellKnownTypes;

namespace Elio.Widgets;

public class WidgetFileUploader : Button, ISessionWidget
{
    private string _mimeType = "*/*";
    private readonly Uri? _file;
    public BaseSession? Session { get; set; }
    public void Init(InitOptions options)
    {
        (WidthRequest, HeightRequest) = (options.Width, options.Height);
        this.SetPoint(options.X, options.Y);
        Text = options.Text;
    }

    public async Task<bool> OnViewReceive(string name, long sid, long fid, params Any[] argv)
    {
        switch (name)
        {
            case "getMimeType":
                await GetMimeType(sid, fid);
                break;

            case "setMimeType":
                SetMimeType(argv);
                break;

            case "getFilename":
                await GetFilename(sid, fid);
                break;

            case "upload":
                Upload();
                break;

            default:
                return false;
        }
        return true;
    }

    private async Task GetMimeType(long sid, long fid) =>
        await Session!.SendAction("onGetMimeType", sid, fid, _mimeType.ToAny());

    private void SetMimeType(params Any[] argv) =>
        _mimeType = argv[0].P2String();

    private async Task GetFilename(long sid, long fid)
    {
        string fileName = _file?.Segments[^1] ?? string.Empty;
        await Session!.SendAction("onGetFilename", sid, fid, fileName.ToAny());
    }

    private static void Upload() { }
}